package com.bobaini.springcloud.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobaini.springcloud.enums.IsDeleteEnum;
import com.bobaini.springcloud.listener.DictListener;
import com.bobaini.springcloud.mapper.DictMapper;
import com.bobaini.springcloud.model.cmn.Dict;
import com.bobaini.springcloud.service.DictService;
import com.bobaini.springcloud.utils.BeanConvertUtils;
import com.bobaini.springcloud.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: liuyi
 * ClassName: Test
 * Version: 1.0.0
 * DateTime: 2021/03/31-10:36:00
 * Description: TODO
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * 根据数据id查询子数据列表
     * keyGenerator:根据包名_类名_方法名_生成我们的key
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChlidData(Long id) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, id).eq(Dict::getIsDeleted, IsDeleteEnum.NO_DELETE.getNum());
        List<Dict> dictList = dictMapper.selectList(lambdaQueryWrapper);
        //向list集合每个dict对象中设置hasChildren
        return dictList.stream().map(dict -> {
            boolean children = this.isChildren(dict.getId());
            dict.setHasChildren(children);
            return dict;
        }).collect(Collectors.toList());
    }

    /**
     * 导出文件
     *
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置下载操作
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            long startTime = System.currentTimeMillis();
            log.info("文件读取之前的时间:{}", startTime);
            List<Dict> dictList = dictMapper.selectList(null);
            /**
             * 参数1:源集合对象
             * 参数2:目标对象
             */
            List<DictEeVo> dictVoList = BeanConvertUtils.commonConvertList(dictList, DictEeVo.class);
            /**
             * 参数1:流地址
             * 参数2:实体类
             */
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
            log.info("文件读取之后的时间:{}", System.currentTimeMillis() - startTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     * allEntries是否清空所有缓存
     * 添加之后, 清楚缓存中的所有数据,同时将入库的结果返回值缓存中
     *
     * @param file
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断id下面是否有子节点
     *
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, id).eq(Dict::getIsDeleted, IsDeleteEnum.NO_DELETE.getNum());
        Integer count = dictMapper.selectCount(lambdaQueryWrapper);
        // 0>0    1>0
        return count > 0;
    }

    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if (StringUtils.isEmpty(parentDictCode)) {
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if (null != dict) {
                return dict.getName();
            }
        } else {
            //医院是需要parentDictCode来区分的
            Dict parentDict = this.getByDictsCode(parentDictCode);
            if (null == parentDict) {
                return "";
            }
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
            if (null != dict) {
                return dict.getName();
            }
        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getByDictsCode(dictCode);
        if (null == codeDict) {
            return null;
        }
        return this.findChlidData(codeDict.getId());
    }


    private Dict getByDictsCode(String parentDictCode) {
        Dict dict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, parentDictCode).eq(Dict::getIsDeleted, 0));
        return dict;
    }
}

